Imports System.Collections.Generic
Imports Cdm.DataCore.LookupTables

Partial Class appStateCustomization
    Inherits System.Web.UI.Page

    Protected Sub btnLogo_Click(ByVal sender As Object, _
                                ByVal e As System.EventArgs) _
                                Handles LogoButton.Click

        ClearStatus()
        FixedContentPanel.Visible = False
        StateScrollingGridView.Visible = False
        NewLogoPanel.Visible = True

    End Sub

    Protected Sub btnUpload_Click(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles UploadButton.Click

        Dim logoObject As Cdm.DataCore.LookupTables.LuApplicationSettings
        logoObject = Cdm.DataCore.LookupTables.LuApplicationSettings.Retrieve("CurrentLogo")

        logoObject.SettingName = "CurrentLogo"
        logoObject.SettingValue = "~\images\" + FileUploadControl.FileName
        logoObject.Persist()
        Application("CurrentLogo") = logoObject.SettingValue

        Dim filePath As String
        filePath = Me.MapPath(Me.Request.ApplicationPath) + "\images\"
        FileUploadControl.SaveAs(filePath + FileUploadControl.FileName)

        Me.NewLogoPanel.Visible = False
        UploadButton.Visible = False

        FixedContentPanel.Visible = True
        UploadMsgLabel.Visible = True

        StateScrollingGridView.DataBind()
        StateScrollingGridView.Visible = True

    End Sub

    Private Sub BindGrid()
        Me.StateScrollingGridView.DataSource = Cdm.DataCore.LookupTables.LuApplicationSettings.ListBySortWithoutLogo("DisplayName")
        Me.StateScrollingGridView.DataBind()
    End Sub
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        BindGrid()
    End Sub


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'If Not Me.IsPostBack Then
        'BindGrid()
        'End If
        SetupJavaScript()
        'If Not Page.IsPostBack Then
        'Me.StateScrollingGridView.Sort("DisplayName", SortDirection.Ascending)
        'End If
    End Sub


    Private Sub SetupJavaScript()

        EntityController.JavaScriptAddChildDiv(Me.StateScrollingGridView.DivClientId, CInt(Me.StateScrollingGridView.ToolTip))
        ClientScript.RegisterStartupScript(Me.GetType(), "scrollDivs", EntityController.JavaScriptScrollingGridStartup(Me.StateScrollingGridView), True)
        EntityController.JavaScriptSetFixedHeight(28)
    End Sub

    Protected Sub StateScrollingGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles StateScrollingGridView.RowCancelingEdit
        SetStatus("Update canceled.")
    End Sub

    Protected Sub StateScrollingGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles StateScrollingGridView.RowCommand
        If e.CommandName.Equals("Update") Then
            Response.Write("Update")
        End If
    End Sub

    Protected Sub StateScrollingGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles StateScrollingGridView.RowDataBound
        If e.Row.DataItemIndex = 0 Then
            AccessibilityController.AddImageToSortableGridHeaders(StateScrollingGridView)
        End If

        Dim setting As Cdm.DataCore.LookupTables.LuApplicationSettings = e.Row.DataItem
        If Not setting Is Nothing Then
            If setting.ControlType.ToUpper().Equals("DROPDOWN") Then
                Dim editInputControl As InputControls.GenericInputControl

                editInputControl = CType(e.Row.FindControl("SettingValueInputControl"), InputControls.GenericInputControl)

                editInputControl.Items.Add("")
                Dim values As String() = setting.Description.Split(",")
                For iItem As Integer = 0 To values.Length - 1
                    editInputControl.Items.Add(values(iItem).Trim())
                Next
                editInputControl.Value = setting.SettingValue
            End If
        End If

        Dim txtDisplay As TextBox = CType(e.Row.FindControl("DisplayTextBox"), TextBox)
        If Not txtDisplay Is Nothing Then
            SetFocus(txtDisplay.ClientID)
        End If

    End Sub

    Protected Sub StateScrollingGridView_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles StateScrollingGridView.RowEditing
        StateScrollingGridView.EditIndex = e.NewEditIndex
        BindGrid()
    End Sub

    Protected Sub StateScrollingGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles StateScrollingGridView.RowUpdating
        Dim key As DataKey
        key = StateScrollingGridView.DataKeys(e.RowIndex)
        Dim id As Integer = Convert.ToInt32(key.Value.ToString())
        Dim appSetting As Cdm.DataCore.LookupTables.LuApplicationSettings
        Dim editInputControl As InputControls.GenericInputControl
        Dim currentRow As GridViewRow = StateScrollingGridView.Rows(e.RowIndex)
        editInputControl = CType(currentRow.FindControl("SettingValueInputControl"), InputControls.GenericInputControl)
        appSetting = Cdm.DataCore.LookupTables.LuApplicationSettings.Retrieve(id)

        ' NewValues show up as Nothing if an empty string is entered in the field.


        appSetting.SettingValue = editInputControl.Value
        'If CType(Me.StateScrollingGridView.Rows(e.RowIndex).Cells(1).Controls(1), TextBox).Text <> "" Then
        'appSetting.SettingValue = e.NewValues(0).ToString()
        'Else
        'appSetting.SettingValue = ""
        'End If



        appSetting.Persist()
        SetStatus("Setting updated.")
        Application(appSetting.DisplayName) = appSetting.DisplayName
        Application(appSetting.SettingName) = appSetting.SettingValue
        'Reset the Application DisplayNames in case on of those settings has been changed.
        System.Web.HttpContext.Current.Application("displayNames") = Cdm.DataCore.Admin.DisplayNames.RetrieveHashTable()

        StateScrollingGridView.EditIndex = -1
        BindGrid()
    End Sub

    Private Sub ClearStatus()
        SetStatus("")
    End Sub
    Private Sub SetStatus(ByVal message As String)
        Dim mymaster As ASP.admin_admin_master = CType(Me.Master, ASP.admin_admin_master)
        mymaster.SetStatus(message)
    End Sub

    Protected Sub SaveSettingsButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveSettingsButton.Click
        Dim settings As List(Of LuApplicationSettings) = LuApplicationSettings.ListBySortWithoutLogo("DisplayName")
        Dim errorList As New ArrayList()
        Dim newValue As String = ""
        Dim trans As New Gentle.Framework.Transaction()
        Try

            For iSetting As Integer = 0 To settings.Count - 1
                Dim key As DataKey
                key = StateScrollingGridView.DataKeys(iSetting)
                Dim id As Integer = Convert.ToInt32(key.Value.ToString())
                Dim appSetting As Cdm.DataCore.LookupTables.LuApplicationSettings = settings(iSetting)
                Dim editInputControl As InputControls.GenericInputControl
                Dim currentRow As GridViewRow = StateScrollingGridView.Rows(iSetting)

                editInputControl = CType(currentRow.FindControl("SettingValueInputControl"), InputControls.GenericInputControl)
                If Not appSetting.SettingValue.ToLower().Equals(editInputControl.Value.ToLower()) Then
                    If appSetting.IsNumeric And Not IsNumeric(editInputControl.Value) Then
                        errorList.Add(String.Concat("Can not save value for ", appSetting.DisplayName, ".  Please enter a number value."))
                    Else
                        appSetting.SettingValue = editInputControl.Value
                        appSetting.Persist(trans)

                    End If
                    
                End If
            Next
            If errorList.Count = 0 Then
                trans.Commit()
                SetStatus("Settings have been saved.")
            Else
                trans.Rollback()
                SetStatus(errorList(0).ToString())
                BindGrid()
            End If

        Catch ex As Exception
            Dim msg As String
            If Not (ex.InnerException Is Nothing) Then
                msg = ex.InnerException.Message
            Else
                msg = ex.Message
            End If
            SetStatus("There was a problem saving the values: " + msg)
            trans.Rollback()
        End Try

    End Sub


    Protected Sub CancelUploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CancelUploadButton.Click
        SetStatus("Upload Cancelled.")
        FixedContentPanel.Visible = True
        StateScrollingGridView.Visible = True
        NewLogoPanel.Visible = False
    End Sub
End Class
